from typing import Tuple, Callable, Any

from openpyxl.cell.cell import column_index_from_string

from core.cell_data_handler import CellDataHandler
from core.excel_data import ExcelData
from core.number_match_item import MatchItem


class MatchValueCellDataHandler(CellDataHandler):

    __slots__ = [
        'data',
        'matches',
        'column',
        'value_handler'
    ]

    def __init__(self, data: ExcelData,
                 matches: Tuple[MatchItem],
                 column: str or int,
                 value_handler: Callable[[Any], Any] or None):
        self.data = data
        self.matches = matches
        self.column = column if isinstance(column, int) else column_index_from_string(column)
        self.value_handler = value_handler

    def __compare(self, s: tuple, t: tuple) -> bool:
        for item in self.matches:
            if not item.is_match(s, t):
                return False
        return True

    def handle(self, row_data: tuple):
        data = self.data.find_row_data(lambda d: self.__compare(row_data, d))
        value = data[self.column - 1] if data is not None else ''
        value = self.value_handler(value) if self.value_handler is not None else value
        return value
